package com.xj.demo.controller;

import com.xj.demo.entity.EsBlog;
import com.xj.demo.repository.EsBlogReactiveRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * <p>  </p>
 *
 * @author xujj
 * @description
 * @date 2024/4/14 12:53
 */
@RestController()
@RequestMapping("/reactiveEs_repository")
@Api(value = "响应式api——repository", tags = "响应式api——repository")
public class ReactiveEsBlog_repositoryController {

    private final EsBlogReactiveRepository reactiveRepository;

    public ReactiveEsBlog_repositoryController(EsBlogReactiveRepository reactiveRepository) {
        this.reactiveRepository = reactiveRepository;
    }

    @PostMapping("/saveBlog")
    @ApiOperation(value = "保存博客", notes = "保存博客")
    public Mono<EsBlog> save(@RequestBody EsBlog esBlog) {
        return reactiveRepository.save(esBlog);
    }

    @PostMapping("/saveAllBlog")
    @ApiOperation(value = "批量保存博客", notes = "批量保存博客")
    public Flux<EsBlog> saveAll(@RequestBody List<EsBlog> list) {
        return reactiveRepository.saveAll(list);
    }

    /**
     * 异步向es存esblog
     *
     * @param list
     * @return
     */
    @PostMapping("/saveAllBlog_reactive")
    @ApiOperation(value = "批量保存博客", notes = "批量保存博客")
    public Flux<EsBlog> saveAll_re(@RequestBody List<EsBlog> list) {
        Flux<EsBlog> flux = Flux.fromIterable(list);
        return reactiveRepository.saveAll(flux);
    }

    @GetMapping("/deleteBlogById")
    @ApiOperation(value = "通过id删除博客", notes = "通过id删除博客")
    public Mono<Void> deleteBlogById(String id) {
        return reactiveRepository.deleteById(id);
    }


    @PostMapping("/deleteAllBlog")
    @ApiOperation(value = "批量删除博客", notes = "批量删除博客")
    public Mono<Void> deleteAll(@RequestBody List<EsBlog> list) {
        return reactiveRepository.deleteAll(list);
    }

    @GetMapping("/searchById/{id}")
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    public Mono<EsBlog> searchById(@PathVariable String id) {
        return reactiveRepository.findById(id);
    }

    @PostMapping("/searchByIds")
    @ApiOperation(value = "通过id批量查询", notes = "通过id批量查询")
    public Flux<EsBlog> searchAll(@RequestBody List<String> ids) {
        return reactiveRepository.findAllById(ids);
    }

    // 查询所有,并根据id倒序排序
    @GetMapping("/findAll")
    @ApiOperation(value = "查询所有", notes = "查询所有")
    public Flux<EsBlog> findAll() {
        return reactiveRepository.findAll(Sort.by("title").descending());
    }
}
